package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.param.ReSendSMSParam
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.MeSandboxFileEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivitySignPassOrderDetailBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterPassSignOrderDetail
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxDialogUpLoadProof
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.viewmodel.OrgRaceViewModel
import com.google.gson.Gson
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File

/**
 * @Author      : hxw
 * @Date        : 2024/7/16 11:44
 * @Describe    : 关塞报名订单
 */
class ActivitySignPassOrderDetail : BaseActivity<OrgRaceViewModel, ActivitySignPassOrderDetailBinding>() {

    private var teamName = ""
    private var mQUrl = ""
    private var ruleFile = ""
    private var mOrderNo = ""
    private var mOrderId = 0
    private var mPayOrderId = 0
    private var appOrderId = 0
    private var traceId = 0
    private val mAdapter: AdapterPassSignOrderDetail by lazy { AdapterPassSignOrderDetail(arrayListOf()) }
    private var proofFile: File? = null
    private var dialog: RxDialogUpLoadProof? = null
    private var payPassDialog: PayPassDialog? = null
    private var payDialog: RxPayDialog? = null
    private var isPaySuccess: Boolean = false//标记是否支付成功

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeOrg.ivOrgIcon.isVisible = false
        appOrderId = intent.getIntExtra("orderId", 0)
        teamName = intent.getStringExtra("teamName").toString()

        showLoading(getString(R.string.loading))
        mViewModel.getAppOrder(appOrderId.toString())

        mDatabind.swipeRefreshLayout.init {
            mViewModel.getAppOrder(appOrderId.toString())
        }

        mDatabind.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)

    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        mViewModel.payNowResult.observe(this) { resultState ->
            parseState(resultState, {
                payPassDialog?.dismiss()
                isPaySuccess = true
                if (payDialog != null && payDialog!!.isShowing)
                    payDialog?.showBottomView()
                paySuccess()
            }, {
                payDialog?.dismiss()
                RxToast.showToast(it.msg)
            })
        }
        /** 重新发送验证码  */
        mViewModel.reSendSMSResult.observe(this) {
            dismissLoading()
            if (it.isSuccess) {
                RxToast.showToast(getString(R.string.send_successfully))
                showPayDialog()
            } else {
                RxToast.showToast(it.errorMsg)
                if (it.errorMsg == "未绑定手机。") {
                    RxToast.warning(getString(R.string.No_mobile_phone_is_attached))
                    return@observe
                }
            }
        }
        /**  关赛报名申请支付  */
        mViewModel.paySign.observe(this) {
            mPayOrderId = it.orderId
            mOrderNo = it.orderNo
            showPayDialog()
        }
        /** 上传缴费凭证(关塞报名)  */
        mViewModel.uploadPayResult.observe(this) {
            dialog?.dismiss()
            mViewModel.getAppOrder(appOrderId.toString())
        }
        /** 获取app订单详情  */
        mViewModel.getAppOrderResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            mDatabind.llOnlinePay.isVisible = it.transformFee == 1
            mDatabind.data = it
            mQUrl = it.qrUrl
            mOrderId = it.orderId
            ruleFile = it.ruleFile
            traceId = it.traceId
            mAdapter.setList(it.list)
            mAdapter.notifyDataSetChanged()
            mDatabind.includeOrg.tvIncludeOrgName.text = it.orgName
            mDatabind.includeOrg.tvIncludeOrgRaceName.text = teamName + "   " + it.aboutPass
            ImageLoaderManager.loadRoundImage(this, ruleFile, mDatabind.ivProofImage, 5)
            val title = when (it.orderStatus) {// 1-未审核 2-已审核 3-待补费 4-待退单 5-已退单 6-已关闭
                1 -> getString(R.string.commit_order_and_check)
                2 -> getString(R.string.order_and_checked)
                3 -> getString(R.string.order_and_bufei)
                4 -> getString(R.string.order_and_td)
                5 -> getString(R.string.order_and_ytd)
                else -> getString(R.string.order_and_closed)

            }
            mDatabind.includeBar.tvTitle.text = title
            mDatabind.llProof.isVisible = it.ruleFile.isNotEmpty()
            mDatabind.llBottom.isVisible = it.orderStatus == 3 || it.orderStatus == 2 || it.orderStatus == 1
        }
    }

    private fun paySuccess() {
        eventViewModel.refundReturnResult.value = true
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent(getString(R.string.payment_success))
        payDialog?.setSureBtnContent(getString(R.string.check_an_order))
        payDialog?.setCancelBtnContent(getString(R.string.closed))
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(this)
        payDialog!!.loadingDialog()
        payDialog!!.setSureListener {
            /** 通知付款成功，刷新数据 */
            eventViewModel.toNoticePaySuccess.value = true
            finish()
            payDialog!!.dismiss()
        }
        payDialog!!.setCancelListener {
            /** 通知付款成功，刷新数据 */
            eventViewModel.toNoticePaySuccess.value = true
            try {
                payDialog!!.dismiss()
                finish()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.llOutlinePay,
            mDatabind.llOnlinePay,
            mDatabind.ivProofImage,
            mDatabind.llOnlinePayWei
        ) {
            when (it) {
                mDatabind.llOnlinePayWei -> showPayWeiChatDialog()
                mDatabind.ivProofImage -> openBigImage(mDatabind.ivProofImage, ruleFile)
                mDatabind.llOnlinePay -> applyPayOrder()
                mDatabind.llOutlinePay -> showDialogProof()
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    private fun showPayWeiChatDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("将打开手机浏览器进行支付!")
        dialog.setSureListener {
//            openBrowserWithUrl()
            openWeiChatLink()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun openWeiChatLink() {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setData(Uri.parse(mQUrl))
        intent.setPackage("com.tencent.mm")
        try {
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
        }
    }



    private fun openBrowserWithUrl() {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(mQUrl)
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        }
    }

    /**  关赛报名申请支付  */
    private fun applyPayOrder() {
        showLoading(getString(R.string.loading))
        val map = mapOf("traceId" to traceId)
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        mViewModel.paySign(body)
    }

    private fun showDialogProof() {
        dialog = RxDialogUpLoadProof(this)
        dialog!!.setIvListener {
            showPop()
        }
        dialog!!.setSureListener {
            showLoading(getString(R.string.loading))
            proofFile?.let { it1 -> mViewModel.uploadPayFile(mOrderId, it1) }
        }
        dialog!!.setFullScreenWidth()
        dialog!!.show()
    }

    private fun showPop() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setSandboxFileEngine(MeSandboxFileEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .setQueryFilterListener { false }
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(true)
            .isPreviewImage(true)
            .isMaxSelectEnabledMask(true)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                if (!result.isNullOrEmpty()) {
                    // 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200）
                    EasyImgCompress.withSinglePic(this@ActivitySignPassOrderDetail, result[0].realPath)
                        .maxPx(1200)
                        .maxSize(1024)
                        .enableLog(true)
                        .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                            override fun onStart() {
                                LogUtils.debugInfo("onStart")
                            }

                            override fun onSuccess(file: File) {
                                proofFile = file
                                if (proofFile!!.exists() && proofFile!!.isFile) {
                                    val bitmap = BitmapFactory.decodeFile(proofFile?.absolutePath)
                                    dialog?.setImage(bitmap)
                                } else {
                                    RxToast.showToast(getString(R.string.pic_upload_fail))
                                }
                            }

                            override fun onError(error: String) {
                                LogUtils.debugInfo("onError error = $error")
                            }
                        }).start()
                }
            }

            override fun onCancel() {}
        })
    }

    private fun showPayDialog() {
        payPassDialog = PayPassDialog(this)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast(getString(R.string.Turn_off_Payment))
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                val body = ReSendSMSParam(orderId = mPayOrderId)
                mViewModel.reSendSMS(body)
            }

            override fun onPassFinish(verifyCode: String?) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val map = mapOf("orderId" to mPayOrderId, "verificationCode" to verifyCode)
                    val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                    mViewModel.payNow(body)
                }, lifecycleScope)
            }
        })
    }
}